#!/usr/bin/env bash

set -eu

source $SNAP/actions/common/utils.sh

use_snap_env

if [ -e ${SNAP_DATA}/var/lock/clustered.lock ]
then
    echo "This MicroK8s deployment is acting as a node in a cluster."
    echo "Use 'snap stop microk8s' to stop services on this node."
    exit 0
fi

exit_if_not_root
exit_if_no_permissions

FORCE=false
PARSED=$(getopt --options=lho: --longoptions=force,help,output: --name "$@" -- "$@")
eval set -- "$PARSED"
while true; do
    case "$1" in
        -h|--help)
            echo "Usage: microk8s stop [OPTIONS]"
            echo
            echo "Stop Kubernetes services"
            echo
            echo "Options:"
            echo " -h, --help          Show this help"
            exit 0
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "microk8s stop: invalid option -- $1"
            exit 1
    esac
done

stopcmd="run_with_sudo snap stop ${SNAP_NAME} --disable"
if is_strict
then
  stopcmd="snapctl stop microk8s.daemon-kubelite --disable"
fi

$stopcmd
stop_status=$?

if ! [ $stop_status -eq 0 ]
then
    echo 'Failed to stop microk8s services. Check snapd logs with "journalctl -u snapd.service"'
    exit 1
else
    if is_strict
    then
      remove_all_containers
      snapctl stop microk8s --disable
    else
      kill_all_container_shims
    fi
    run_with_sudo touch ${SNAP_DATA}/var/lock/stopped.lock
fi
